<?php
class Commwap_model extends Base_Model
{
    private $_resource_url;
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->helper('url');
        $this->_resource_url = $this->config->item('resource_url');
        $this->_media_url = $this->config->item('media_url');
    }

    public function getData($table,$select='*',$where=array(),$offset = 0,$limit = 0,$sortkey = '',$sorttype = 'ASC')
    {
        $this->db->select($select)->from($table);
        if (!empty($where)) $this->db->where($where);
        if (!empty($limit)) $this->db->limit($limit,$offset);
        if (!empty($sortkey)) $this->db->order_by($sortkey,$sorttype);
        return $this->db->get()->result_array();
    }

    public function getRowData($table,$select='*',$where=array())
    {
        $this->db->select($select)->from($table);
        if (!empty($where)) $this->db->where($where);
        $this->db->limit(1);
        return $this->db->get()->row_array();
    }

    public function formatnum($num,$type='',$id='')
    {
//        $num = strlen((string)$num)>3?round((float)$num/1000,1).'K':(string)$num;
        if ($type==='views'){
            $change=array(
                /*童年的秘密解读*/
                '30'=>3,
                /*童年的秘密答疑*/
                '37'=>3,
                /*爱的艺术解读*/
                '38'=>3,
                /*爱的艺术答疑*/
                '39'=>3,
                /*卡尔威特的教育解读*/
                '40'=>2,
                /*卡尔威特的教育答疑*/
                '41'=>2,
                /*家庭教育解读*/
                '42'=>3,
                /*家庭教育答疑*/
                '43'=>3,
                /*孩子挑战解读*/
                '44'=>3,
                /*孩子挑战解读*/
                '45'=>3,
                /*亲子关系全面技巧解读*/
                '46'=>3,
                /*亲子关系全面技巧答疑*/
                '47'=>3,
                /*多元智能新视野解读*/
                '48'=>3,
                '49'=>3,
                /*多元智能新视野答疑*/
                '50'=>3,
                /*游戏力解读*/
                '51'=>2,
                '52'=>2,
                '53'=>2,
                /*游戏力答疑*/
                '54'=>3,
                /*儿童技能教养法解读*/
                '55'=>3,
                /*儿童技能教养法答疑*/
                '56'=>3,
                /*正面管教解读*/
                '57'=>3,
                /*正面管教答疑*/
                '58'=>3,
                /*PET父母效能训练手册解读*/
                '59'=>3,
                /*PET父母效能训练手册答疑*/
                '60'=>3,
                /*非暴力沟通解读*/
                '61'=>3,
                /*非暴力沟通答疑*/
                '62'=>3
            );
            if (isset($change[$id])) $num*=$change[$id];
        }
        if ($num>100000) $num='1000000+';
        return $num;
    }
    /******发现页******/
    public function getBanner()
    {
        $data = $this->getData('comm_banner','title,link,bannerurl,external','',0,0,'sort','ASC');
        $res = array();
        foreach ($data as $row){
            $resrow['title'] = $row['title'];
            $resrow['link'] = $row['link'];
            $resrow['bannerurl'] = $this->_resource_url.$row['bannerurl'];
            $resrow['external'] = $row['external'];
            $res[] = $resrow;
        }
        return $res;
    }

    public function getSubject()
    {
        $data = $this->getData('comm_subject','id,name,icon','status in (1,2)',0,0,'sort','ASC');
        $res = array();
        foreach ($data as $row){
            $resrow['id'] = $row['id'];
            $resrow['name'] = $row['name'];
            $resrow['icon'] = $this->_resource_url.$row['icon'];
            $res[] = $resrow;
        }
        return $res;
    }

    public function getEditSubject()
    {
        $data = $this->getData('comm_subject','id,name,icon','status in (1,3)',0,0,'sort','ASC');
        $res = array();
        foreach ($data as $row){
            $resrow['id'] = $row['id'];
            $resrow['name'] = $row['name'];
            $resrow['icon'] = $this->_resource_url.$row['icon'];
            $res[] = $resrow;
        }
        return $res;
    }

    public function getQuestionWithUser($offset,$limit)
    {
        $sql = "SELECT q.id,q.question,q.description,q.isresponsed,u.userName,u.userIcon ".
            "FROM comm_question AS q ".
            "LEFT JOIN mod_user AS u ".
            "on u.uid = q.uid ".
            "where q.status = 1 ".
            "ORDER BY q.score DESC,q.created DESC ".
            "LIMIT ".$offset.",".$limit;
        $res = $this->db->query($sql)->result_array();

        $length = count($res);
        if($length<$limit) $end=1;
        else $end = 0;

        if ($length !== 0){
            $this->load->model('redis_model');
            $redis = $this->redis_model->getRedisInstance();
            $redis->multi();
            foreach ($res as $row){
                $redis->hMGet('question:'.$row['id'],array('views','follows'));
            }
            $data = $redis->exec();
            foreach ($res as $k=>&$row) {
                $row['userIcon'] = preg_match("/http:\/\//i",$row['userIcon'])>0?$row['userIcon']:$this->_resource_url.$row['userIcon'];
                $row['views'] = $this->formatnum($data[$k]['views'],'views',$row['id']);
                $row['follows'] = $this->formatnum($data[$k]['follows']);
            }
        }

        return array('question'=>$res,'end'=>$end);
    }
    /******话题页******/
    public function getSubjectById($id,$uid)
    {
        $res = $this->getRowData('comm_subject','icon,name,description',array('id'=>$id));
        if (!empty($res)){
            $this->load->model('redis_model');
            $data = $this->redis_model->hmget('subject:'.$id,array('follows','questions'));
            $isfollowed = $this->redis_model->sismember('user:'.$uid.'.subfollows',$id);
            /*重构数据*/
            $res['icon'] = $this->_resource_url.$res['icon'];
            $res['follows'] = $this->formatnum($data['follows']);
            $res['questions'] = $this->formatnum($data['questions']);
            $res['isfollowed'] = $isfollowed;
        }
        return $res;
    }

    public function getQuestionBysid($sid,$offset,$limit,$sort)
    {
        $sql = "SELECT sq.qid as id,q.question,q.description,q.isresponsed,u.userName,u.userIcon ".
            "FROM comm_subq_relations as sq ".
            "LEFT JOIN comm_question as q ON sq.qid = q.id ".
            "LEFT JOIN mod_user as u ON u.uid = q.uid ".
            "WHERE sq.subid = ".$sid." AND q.status = 1 ";
        if ($sort==='score') $sql.="ORDER BY q.score DESC,q.created DESC ";
        else $sql.= "ORDER BY q.created DESC ";
        $sql.="LIMIT ".$offset.",".$limit;
        $res = $this->db->query($sql)->result_array();

        $length = count($res);
        if ($length<$limit) $end = 1;
        else $end = 0;

        if ($length !== 0){
            $this->load->model('redis_model');
            $redis = $this->redis_model->getRedisInstance();
            $redis->multi();
            foreach ($res as $row){
                $redis->hMGet('question:'.$row['id'],array('views','follows'));
            }
            $data = $redis->exec();
            /*重构数据*/
            foreach ($res as $k=>&$row) {
                $row['userIcon'] = preg_match("/http:\/\//i",$row['userIcon'])>0?$row['userIcon']:$this->_resource_url.$row['userIcon'];
                $row['views'] = $this->formatnum($data[$k]['views'],'views',$row['id']);
                $row['follows'] = $this->formatnum($data[$k]['follows']);
            }
        }

        return array('question'=>$res,'end'=>$end);
    }

    public function followSub($sid,$uid)
    {
        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $redis->multi();
        $redis->sAdd('subject:'.$sid.'.follows',$uid);
        $redis->sAdd('user:'.$uid.'.subfollows',$sid);
        $redis->exec();
        $follows = $redis->sCard('subject:'.$sid.'.follows');
        $redis->hSet('subject:'.$sid,'follows',$follows);
        return true;
    }

    public function cancelfollowSub($sid,$uid)
    {
        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $redis->multi();
        $redis->sRem('subject:'.$sid.'.follows',$uid);
        $redis->sRem('user:'.$uid.'.subfollows',$sid);
        $redis->exec();
        $follows = $redis->sCard('subject:'.$sid.'.follows');
        $redis->hSet('subject:'.$sid,'follows',$follows);
        return true;
    }
    /******问题页******/
    public function readQuestion($qid,$uid)
    {
        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $isread = $redis->getBit('question:'.$qid.'.viewsraw',$uid);
        if ($isread==0){
            $op = array('type'=>'rq','data'=>array('qid'=>$qid,'uid'=>$uid));
            $op = igbinary_serialize($op);

            $redis->multi();
            $redis->setBit('question:'.$qid.'.viewsraw',$uid,1);
            $redis->bitCount('question:'.$qid.'.viewsraw');
            $data = $redis->exec();
            $views = $data[1];
            $redis->hSet('question:'.$qid,'views',$views);
            $redis->rPush('qoplist',$op);
            return true;
        }else{return false;}
    }

    public function getQWithUserById($id,$uid)
    {
        $res = $this->db->select('id,question,description,isresponsed,anslink')->from('comm_question')->limit(1)->where('id = '.$id)->get()->row_array();
        if (!empty($res)){
            $this->load->model('redis_model');
            $data = $this->redis_model->hmget('question:'.$res['id'],array('views','follows','answers'));
            $isfollowed = $this->redis_model->sismember('user:'.$uid.'.follows',$res['id']);

            $res['views'] = $this->formatnum($data['views'],'views',$id);
            $res['follows'] = $this->formatnum($data['follows']);
            $res['answers'] = $this->formatnum($data['answers']);
            $res['isfollowed'] = $isfollowed;
        }
        return $res;
    }

    public function getQContributer($qid,$limit)
    {
        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $redis->multi();
        $redis->zRevRange('question:'.$qid.'.beansrank',0,$limit-1);
        $redis->zCard('question:'.$qid.'.beansrank');
        $redis->hGet('question:'.$qid,'beans');
        $res = $redis->exec();
        $uids = $res[0];
        $contrnum = strlen((string)$res[1])>3?round((float)$res[1]/1000,1).'K':(string)$res[1];
        $beansnum = strlen((string)$res[2])>3?round((float)$res[2]/1000,1).'K':(string)$res[2];
        if (!empty($uids)){
            $data = $this->db->select('userIcon')->from('mod_user')->where_in('uid',$uids)->get()->result_array();
            $length = count($data);
            if ($length<$limit) $over=0;
            else $over=1;
            foreach($data as &$row){
                $row['userIcon'] = preg_match("/http:\/\//i",$row['userIcon'])>0?$row['userIcon']:$this->_resource_url.$row['userIcon'];
            }
            return array('contributer'=>$data,'over'=>$over,'contrnum'=>$contrnum,'beansnum'=>$beansnum);
        }else{return array('contributer'=>'','over'=>0,'contrnum'=>'','beansnum'=>'');}
    }

    public function addQuestion($data,$subdata)
    {
        $this->db->insert('comm_question',$data);
        $id = $this->db->insert_id();
        if (!empty($id)){
            $this->load->model('redis_model');
            $redis = $this->redis_model->getRedisInstance();
            $redis->multi()
                ->set('question:'.$id.'.viewsraw','')
                ->hMSet('question:'.$id,array('id'=>$id,'uid'=>$data['uid'],'views'=>0,'follows'=>0,'beans'=>0,'answers'=>0,'created'=>time()))
                ->exec();

            if ($subdata['subid']>0){
                $subdata['qid'] = $id;
                $this->db->insert('comm_subq_relations',$subdata);
                $subqid = $this->db->insert_id();
                if (!empty($subqid)){
                    $op = array('type'=>'addq','data'=>array('uid'=>$data['uid'],'qid'=>$id,'subid'=>$subdata['subid']));
                    $op = igbinary_serialize($op);
                    $redis->multi();
                    $redis->hIncrBy('subject:'.$subdata['subid'],'questions',1);
                    $redis->rPush('notifydeliver',$op);
                    $redis->exec();
                }
            }

            $res = array('qid'=>$id,'firstq'=>false);
            if ($redis->getBit('comm:firstq',$data['uid'])==0){
                $redis->multi()
                    ->setBit('comm:firstq',$data['uid'],1)
                    ->incrBy('user:'.$data['uid'].'.beans',100)
                    ->exec();
                $res['firstq']=true;
            }
        }else{$res = false;}
        return $res;
    }

    public function getBeansrankByQid($qid,$start,$end,$limit)
    {
        $this->load->model('redis_model');
        $data = $this->redis_model->zrevrange('question:'.$qid.'.beansrank',$start,$end,true);
        if(!empty($data)){
            $uids = array_keys($data);
            $res = $this->db->select('uid,userName,userIcon')->from('mod_user')->where_in('uid',$uids)->get()->result_array();

            $length = count($res);
            if ($length < $limit) $pageend = 1;
            else $pageend = 0;

            $format = array();
            foreach ($res as $row){
                $format[$row['uid']]['userName']=$row['userName'];
                $format[$row['uid']]['userIcon']=preg_match("/http:\/\//i",$row['userIcon'])>0?$row['userIcon']:$this->_resource_url.$row['userIcon'];
            }

            $i = 1;
            foreach ($data as $k=>$v) {
                $rank[$i]['index'] = $i;
                $rank[$i]['userName'] = $format[$k]['userName'];
                $rank[$i]['userIcon'] = $format[$k]['userIcon'];
                $rank[$i]['beansnum'] = $v;
                $i++;
            }
            return array('rank'=>array_values($rank),'end'=>$pageend);
        }else{return array('rank'=>'','end'=>1);}

    }
    public function getQuestionrank($start,$end,$limit)
    {
        $this->load->model('redis_model');
        $data = $this->redis_model->zrevrange('question:beansrank',$start,$end,true);
        if(!empty($data)){
            $qids = array_keys($data);
            $res = $this->db->select('q.id as qid,q.question,u.userName,u.userIcon')
                ->from('comm_question as q')
                ->join('mod_user as u','u.uid=q.uid','left')
                ->where_in('q.id',$qids)
                ->where(array('q.status'=>1))
                ->get()->result_array();

            $length = count($res);
            if ($length < $limit) $pageend = 1;
            else $pageend = 0;

            $format = array();
            foreach ($res as $row){
                $format[$row['qid']]['qid']=$row['qid'];
                $format[$row['qid']]['question']=$row['question'];
                $format[$row['qid']]['userName']=$row['userName'];
                $format[$row['qid']]['userIcon']=preg_match("/http:\/\//i",$row['userIcon'])>0?$row['userIcon']:$this->_resource_url.$row['userIcon'];
            }

            $i = 1;
            foreach ($data as $k=>$v) {
                $rank[$i]['index'] = $i;
                $rank[$i]['qid'] = $format[$k]['qid'];
                $rank[$i]['question'] = $format[$k]['question'];
                $rank[$i]['userName'] = $format[$k]['userName'];
                $rank[$i]['userIcon'] = $format[$k]['userIcon'];
                $rank[$i]['beansnum'] = $this->formatnum($v);
                $i++;
            }
            return array('rank'=>array_values($rank),'end'=>$pageend);
        }else{return array('rank'=>'','end'=>1);}

    }

    public function getQResponsed($offset,$limit)
    {
        $res = $this->db->select('q.id as qid,q.question,u.userName,u.userIcon,a.created')
            ->from('comm_answer_audio as a')
            ->join('comm_question as q','q.id=a.qid','left')
            ->join('mod_user as u','u.uid=q.uid','left')
            ->order_by('a.created','DESC')
            ->where(array('q.status'=>1))
            ->limit($limit,$offset)
            ->get()->result_array();

        $length = count($res);
        if ($length < $limit) $pageend = 1;
        else $pageend = 0;

        if (!empty($res)){
            foreach ($res as &$row){
                $row['created']=date('Y-m-d',$row['created']);
                $row['userIcon']=preg_match("/http:\/\//i",$row['userIcon'])>0?$row['userIcon']:$this->_resource_url.$row['userIcon'];
            }
            return array('qlist'=>$res,'end'=>$pageend);
        }else{return array('qlist'=>'','end'=>1);}
    }

    public function getAnswersByqid($qid,$offset,$limit,$sort='score')
    {
        $sql = "SELECT a.id,a.answer,a.changed,u.userName,u.userIcon ".
            "FROM comm_answer AS a ".
            "LEFT JOIN mod_user AS u ".
            "on u.uid = a.uid ".
            "WHERE a.qid = ".$qid." ";
        if ($sort==='score') $sql.="ORDER BY a.score DESC,a.created DESC ";
        else $sql.="ORDER BY a.created DESC ";
        $sql.="LIMIT ".$offset.",".$limit;
        $res = $this->db->query($sql)->result_array();

        $length = count($res);
        if ($length<$limit) $end = 1;
        else $end = 0;
        /*获取答案的赞同数和评论数*/
        if ($length !== 0){
            $this->load->model('redis_model');
            $redis = $this->redis_model->getRedisInstance();
            $redis->multi();
            foreach ($res as $row){
                $redis->hMGet('answer:'.$row['id'],array('agrees','comments'));
            }
            $data = $redis->exec();
            /*重构数据*/
            foreach ($res as $k=>&$row) {
                $row['userIcon'] = preg_match("/http:\/\//i",$row['userIcon'])>0?$row['userIcon']:$this->_resource_url.$row['userIcon'];
                $row['agrees'] = $this->formatnum($data[$k]['agrees']);
                $row['comments'] = $this->formatnum($data[$k]['comments']);

                $diff = (float)(time() - $row['changed']);
                if ($diff<60){
                    $row['changed']='1分钟前';
                }elseif($diff>59 && $diff<3600){
                    $min = floor($diff/60);
                    $row['changed']=$min.'分钟前';
                }elseif($diff>3599&&$diff<86400){
                    $hour = floor($diff/3600);
                    $row['changed']=$hour.'小时前';
                }elseif($diff>86399&&$diff<2678400){
                    $day = floor($diff/3600/24);
                    $row['changed']=$day.'天前';
                }elseif($diff>2678399&&$diff<31536000){
                    $month = floor($diff/3600/24/31);
                    $row['changed']=$month.'个月前';
                }else{
                    $year = floor($diff/3600/24/365);
                    $row['changed']=$year.'年前';
                }
            }
        }

        return array('answer'=>$res,'end'=>$end);
    }

    public function followQuestion($qid,$uid)
    {
        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();

        $redis->multi();
        $redis->sAdd('question:'.$qid.'.follows',$uid);
        $redis->sAdd('user:'.$uid.'.follows',$qid);
        $redis->sCard('question:'.$qid.'.follows');
        $redis->hGet('question:'.$qid,'uid');
        $data = $redis->exec();

        $follows = $data[2];
        $op = array('type'=>'fq','data'=>array('uid'=>$uid,'qid'=>$qid));
        $op = igbinary_serialize($op);

        $redis->multi();
        $redis->hSet('question:'.$qid,'follows',$follows);
        $redis->sAdd('user:'.$data[3].'.followers',$uid);
        $redis->rPush('qoplist',$op);
        $redis->rPush('notifydeliver',$op);
        $redis->exec();

        return true;
    }

    public function cancelfollowQuestion($qid,$uid)
    {
        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();

        $redis->multi();
        $redis->sRem('question:'.$qid.'.follows',$uid);
        $redis->sRem('user:'.$uid.'.follows',$qid);
        $redis->sCard('question:'.$qid.'.follows');
        $redis->hGet('question:'.$qid,'uid');
        $data = $redis->exec();

        $follows = $data[2];
        $op = array('type'=>'cq','data'=>array('uid'=>$uid,'qid'=>$qid));
        $op = igbinary_serialize($op);

        $redis->multi();
        $redis->hSet('question:'.$qid,'follows',$follows);
        $redis->sRem('user:'.$data[3].'.followers',$uid);
        $redis->rPush('qoplist',$op);
        $redis->exec();
        return true;
    }

    public function checkAnswerExist($qid,$uid)
    {
        $res = $this->getRowData('comm_answer','id,answer',array('qid'=>$qid,'uid'=>$uid));
        if (empty($res)) return false;
        else return $res;
    }

    public function getAWithUserById($id,$uid)
    {
        $sql = "SELECT a.id,a.qid,q.question,a.answer,u.userName,u.userIcon ".
            "FROM comm_answer AS a ".
            "LEFT JOIN mod_user AS u ".
            "on u.uid = a.uid ".
            "LEFT JOIN comm_question AS q ".
            "on a.qid = q.id ".
            "WHERE a.id = ".$id." LIMIT 1";
        $res = $this->db->query($sql)->row_array();
        if (!empty($res)){
            $this->load->model('redis_model');
            $redis = $this->redis_model->getRedisInstance();
            $redis->multi();
            $redis->hMGet('answer:'.$res['id'],array('agrees','comments','collects'));
            $redis->sIsMember('user:'.$uid.'.collects',$id);
            $redis->getBit('answer:'.$id.'.agreesraw',$uid);
            $data = $redis->exec();
            /*重构数据*/
            $res['userIcon'] = preg_match("/http:\/\//i",$res['userIcon'])>0?$res['userIcon']:$this->_resource_url.$res['userIcon'];
            $res['agrees'] = $this->formatnum($data[0]['agrees']);
            $res['comments'] = $this->formatnum($data[0]['comments']);
            $res['collects'] = $this->formatnum($data[0]['collects']);
            $res['isCollected'] = $data[1];
            $res['isAgreed'] = $data[2];
        }
        return $res;
    }

    public function updateAnswer($aid,$data)
    {
        return $this->db->update('comm_answer',$data,array('id'=>$aid));
    }

    public function addAnswer($data)
    {
        $this->db->insert('comm_answer',$data);
        $id = $this->db->insert_id();
        if (!empty($id)){
            $op = array('type'=>'addans','data'=>array('uid'=>$data['uid'],'qid'=>$data['qid'],'aid'=>$id));
            $op = igbinary_serialize($op);

            $this->load->model('redis_model');
            $redis = $this->redis_model->getRedisInstance();
            $redis->multi()
                ->set('answer:'.$id.'.agreesraw','')
                ->hMSet('answer:'.$id,array('id'=>$id,'uid'=>$data['uid'],'qid'=>$data['qid'],'agrees'=>0,'comments'=>0,'collects'=>0,'created'=>time()))
                ->sAdd('user:'.$data['uid'].'.answers',$data['qid'])
                ->hIncrBy('question:'.$data['qid'],'answers',1)
                ->rPush('qoplist',$op)
                ->rPush('notifydeliver',$op)
                ->exec();

            $res = array('aid'=>$id,'firstans'=>false);
            if ($redis->getBit('comm:firstans',$data['uid'])==0){
                $redis->multi()
                    ->setBit('comm:firstans',$data['uid'],1)
                    ->incrBy('user:'.$data['uid'].'.beans',100)
                    ->exec();
                $res['firstans']=true;
            }

        }else{$res = false;}
        return $res;
    }

    public function agreeAnswer($aid,$uid)
    {
        $op = array('type'=>'agrans','data'=>array('uid'=>$uid,'aid'=>$aid));
        $op = igbinary_serialize($op);

        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $redis->multi();
        $redis->setBit('answer:'.$aid.'.agreesraw',$uid,1);
        $redis->bitCount('answer:'.$aid.'.agreesraw');
        $redis->sAdd('user:'.$uid.'.agrees',$aid);
        $redis->hGet('answer:'.$aid,'uid');
        $data = $redis->exec();

        $agrees = $data[1];
        $redis->multi();
        $redis->hSet('answer:'.$aid,'agrees',$agrees);
        $redis->sAdd('user:'.$data[3].'.agreers',$uid);
        $redis->rPush('ansoplist',$op);
        $redis->rPush('notifydeliver',$op);
        $redis->exec();
        return true;
    }

    public function cancelagreeAnswer($aid,$uid)
    {
        $op = array('type'=>'cagrans','data'=>array('uid'=>$uid,'aid'=>$aid));
        $op = igbinary_serialize($op);

        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $redis->multi();
        $redis->setBit('answer:'.$aid.'.agreesraw',$uid,0);
        $redis->bitCount('answer:'.$aid.'.agreesraw');
        $redis->sRem('user:'.$uid.'.agrees',$aid);
        $redis->hGet('answer:'.$aid,'uid');
        $data = $redis->exec();

        $agrees = $data[1];
        $redis->multi();
        $redis->hSet('answer:'.$aid,'agrees',$agrees);
        $redis->sRem('user:'.$data[3].'.agreers',$uid);
        $redis->rPush('ansoplist',$op);
        $redis->exec();

        return true;
    }

    public function collectAnswer($aid,$uid)
    {
        $op = array('type'=>'collans','data'=>array('uid'=>$uid,'aid'=>$aid));
        $op = igbinary_serialize($op);

        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $redis->multi();
        $redis->sAdd('answer:'.$aid.'.collects',$uid);
        $redis->sAdd('user:'.$uid.'.collects',$aid);
        $redis->sCard('answer:'.$aid.'.collects');
        $redis->hGet('answer:'.$aid,'uid');
        $data = $redis->exec();

        $redis->multi();
        $redis->hSet('answer:'.$aid,'collects',$data[2]);
        $redis->sAdd('user:'.$data[3].'.collecters',$uid);
        $redis->rPush('ansoplist',$op);
        $redis->rPush('notifydeliver',$op);
        $redis->exec();

        return true;
    }

    public function cancelcollectAnswer($aid,$uid)
    {
        $op = array('type'=>'ccollans','data'=>array('uid'=>$uid,'aid'=>$aid));
        $op = igbinary_serialize($op);

        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $redis->multi();
        $redis->sRem('answer:'.$aid.'.collects',$uid);
        $redis->sRem('user:'.$uid.'.collects',$aid);
        $redis->sCard('answer:'.$aid.'.collects');
        $redis->hGet('answer:'.$aid,'uid');
        $data = $redis->exec();

        $redis->multi();
        $redis->hSet('answer:'.$aid,'collects',$data[2]);
        $redis->sRem('user:'.$data[3].'.collecters',$uid);
        $redis->rPush('ansoplist',$op);
        $redis->exec();

        return true;
    }

    public function getCommentsByaid($aid,$offset,$limit,$sort='score',$uid)
    {
        $sql = "SELECT c.id,c.comments,c.created,u.userName,u.userIcon ".
            "FROM comm_comments AS c ".
            "LEFT JOIN mod_user AS u ".
            "on u.uid = c.uid ".
            "WHERE c.answerid = ".$aid." ";
        if ($sort==='score') $sql.="ORDER BY c.score DESC,c.created DESC ";
        else $sql.= "ORDER BY c.created DESC ";
        $sql.="LIMIT ".$offset.",".$limit;
        $res = $this->db->query($sql)->result_array();

        $length = count($res);
        if ($length<$limit) $end = 1;
        else $end = 0;
        /*获取评论的点赞数和回复数*/
        if ($length !== 0){
            $this->load->model('redis_model');
            $redis = $this->redis_model->getRedisInstance();
            $redis->multi();
            foreach ($res as $row){
                $redis->hMGet('comment:'.$row['id'],array('thumbups','responses'));
            }
            $data = $redis->exec();

            $redis->multi();
            foreach ($res as $row){
                $this->redis_model->getbit('comment:'.$row['id'].'.thumbupsraw',$uid);
            }
            $isThumbup = $redis->exec();

            /*重构数据*/
            foreach ($res as $k=>&$row) {
                $row['userIcon'] = preg_match("/http:\/\//i",$row['userIcon'])>0?$row['userIcon']:$this->_resource_url.$row['userIcon'];
                $row['thumbups'] = $this->formatnum($data[$k]['thumbups']);
                $row['responses'] = $data[$k]['responses'];
                $row['isThumbup'] = $isThumbup[$k];

                $diff = (float)(time() - $row['created']);
                if ($diff<60){
                    $row['created']='1分钟前';
                }elseif($diff>59 && $diff<3600){
                    $min = floor($diff/60);
                    $row['created']=$min.'分钟前';
                }elseif($diff>3599&&$diff<86400){
                    $hour = floor($diff/3600);
                    $row['created']=$hour.'小时前';
                }elseif($diff>86399&&$diff<2678400){
                    $day = floor($diff/3600/24);
                    $row['created']=$day.'天前';
                }elseif($diff>2678399&&$diff<31536000){
                    $month = floor($diff/3600/24/31);
                    $row['created']=$month.'个月前';
                }else{
                    $year = floor($diff/3600/24/365);
                    $row['created']=$year.'年前';
                }
            }
        }

        return array('comment'=>$res,'end'=>$end);
    }

    public function addComment($data)
    {
        $this->db->insert('comm_comments',$data);
        $id = $this->db->insert_id();
        if (!empty($id)){
            $op = array('type'=>'addcom','data'=>array('uid'=>$data['uid'],'aid'=>$data['answerid'],'cid'=>$id));
            $op = igbinary_serialize($op);

            $this->load->model('redis_model');
            $redis = $this->redis_model->getRedisInstance();
            $redis->multi()
                ->set('comment:'.$id.'.thumbupsraw','')
                ->hMSet('comment:'.$id,array('id'=>$id,'uid'=>$data['uid'],'aid'=>$data['answerid'],'thumbups'=>0,'responses'=>0,'created'=>time()))
                ->hIncrBy('answer:'.$data['answerid'],'comments',1)
                ->rPush('ansoplist',$op)
                ->rPush('notifydeliver',$op)
                ->exec();
        }else{$id = false;}
        return $id;
    }

    public function thumbup($cid,$uid)
    {
        $op = array('type'=>'upcom','data'=>array('uid'=>$uid,'cid'=>$cid));
        $op = igbinary_serialize($op);

        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $redis->multi();
        $redis->setBit('comment:'.$cid.'.thumbupsraw',$uid,1);
        $redis->bitCount('comment:'.$cid.'.thumbupsraw');
        $data = $redis->exec();
        $thumbups = $data[1];
        $redis->hSet('comment:'.$cid,'thumbups',$thumbups);
        $redis->rPush('comoplist',$op);

        return true;
    }

    public function cancelThumbup($cid,$uid)
    {
        $op = array('type'=>'cupcom','data'=>array('uid'=>$uid,'cid'=>$cid));
        $op = igbinary_serialize($op);

        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $redis->multi();
        $redis->setBit('comment:'.$cid.'.thumbupsraw',$uid,0);
        $redis->bitCount('comment:'.$cid.'.thumbupsraw');
        $data = $redis->exec();
        $thumbups = $data[1];
        $redis->hSet('comment:'.$cid,'thumbups',$thumbups);
        $redis->rPush('comoplist',$op);

        return true;
    }

    public function responseComm($data)
    {
        $this->db->insert('comm_comment_response',$data);
        $id = $this->db->insert_id();
        if (!empty($id)){
            $op = array('type'=>'rescom','data'=>array('uid'=>$data['uid'],'cid'=>$data['commentid'],'rid'=>$id));
            $op = igbinary_serialize($op);

            $this->load->model('redis_model');
            $redis = $this->redis_model->getRedisInstance();
            $redis->multi();
            $redis->sAdd('comment:'.$data['commentid'].'.response',$id);
            $redis->sCard('comment:'.$data['commentid'].'.response');
            $res = $redis->exec();
            $rnum = $res[1];
            $redis->hSet('comment:'.$data['commentid'],'responses',$rnum);
            $redis->rPush('comoplist',$op);
        }else{$id = false;}
        return $id;
    }

    public function getResponseBycid($cid,$offset,$limit)
    {
        $sql = "SELECT r.comments,u.userName ".
            "FROM comm_comment_response AS r ".
            "LEFT JOIN mod_user AS u ".
            "on u.uid = r.uid ".
            "WHERE r.commentid = ".$cid." ".
            "ORDER BY r.created DESC ".
            "LIMIT ".$offset.",".$limit;
        $res = $this->db->query($sql)->result_array();

        $length = count($res);
        if ($length<$limit) $end = 1;
        else $end = 0;

//        if ($length !== 0){
//            /*重构数据*/
//            foreach ($res as &$row) {
//
//                $diff = (float)(time() - $row['created']);
//                if ($diff<60){
//                    $row['created']='1分钟前';
//                }elseif($diff>59 && $diff<3600){
//                    $min = floor($diff/60);
//                    $row['created']=$min.'分钟前';
//                }elseif($diff>3599&&$diff<86400){
//                    $hour = floor($diff/3600);
//                    $row['created']=$hour.'小时前';
//                }elseif($diff>86399&&$diff<2678400){
//                    $day = floor($diff/3600/24);
//                    $row['created']=$day.'天前';
//                }elseif($diff>2678399&&$diff<31536000){
//                    $month = floor($diff/3600/24/31);
//                    $row['created']=$month.'个月前';
//                }else{
//                    $year = floor($diff/3600/24/365);
//                    $row['created']=$year.'年前';
//                }
//            }
//        }

        return array('response'=>$res,'end'=>$end);
    }

    public function getUcenterInfo($uid)
    {
        $user = $this->getRowData('mod_user','userName,userIcon',array('uid'=>$uid));
        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $today = date('Ymd',time());
        $redis->multi();
        $redis->sCard('user:'.$uid.'.answers');
        $redis->sCard('user:'.$uid.'.follows');
        $redis->sCard('user:'.$uid.'.subfollows');
        $redis->sCard('user:'.$uid.'.collects');
        $redis->get('user:'.$uid.'.beans');
        $redis->getBit('user:'.$today.'.sign',$uid);
        $data = $redis->exec();
        $beans = $data[4] === false?'0':$data[4];
        $user['userIcon'] = preg_match("/http:\/\//i",$user['userIcon'])>0?$user['userIcon']:$this->_resource_url.$user['userIcon'];
        $res = array('userName'=>$user['userName'],'userIcon'=>$user['userIcon'],'beans'=>$beans,'issigned'=>$data[5],'answers'=>$data[0],'followq'=>$data[1],'followsub'=>$data[2],'collecta'=>$data[3]);
        return $res;
    }

    public function getUserInfo($uid)
    {
        $user = $this->getRowData('mod_user','userName,userIcon',array('uid'=>$uid));
        $user['userIcon'] = preg_match("/http:\/\//i",$user['userIcon'])>0?$user['userIcon']:$this->_resource_url.$user['userIcon'];
        $res = array('userName'=>$user['userName'],'userIcon'=>$user['userIcon']);
        return $res;
    }

    public function sign($uid)
    {
        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $today = date('Ymd',time());
        $res1 = $redis->getBit('user:'.$today.'.sign',$uid);
        if ($res1 == 0){
            $res2 = $redis->multi()->setBit('user:'.$today.'.sign',$uid,1)->incrBy('user:'.$uid.'.beans',10)->exec();
            return array('beans'=>$res2[1]);
        }else{return array('beans'=>0);}
    }

    public function charge($uid,$num)
    {
        $this->load->model('redis_model');
        $res = $this->redis_model->incrby('user:'.$uid.'.beans',$num);
        return array('beans'=>$res);
    }

    public function decharge($uid,$qid,$num)
    {
        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $beans = $redis->get('user:'.$uid.'.beans');
        if (((int)$beans-$num)<0) return false;
        $op = array('type'=>'cbeans','data'=>array('uid'=>$uid,'qid'=>$qid,'num'=>$num));
        $op = igbinary_serialize($op);

        $redis->multi();
        $redis->decrBy('user:'.$uid.'.beans',$num);
        $redis->hIncrBy('question:'.$qid,'beans',$num);
        $redis->zIncrBy('question:beansrank',$num,$qid);
        $redis->zIncrBy('question:'.$qid.'.beansrank',$num,$uid);
        $redis->zCard('question:'.$qid.'.beansrank');
        $redis->rPush('qoplist',$op);
        $redis->rPush('notifydeliver',$op);
        $data = $redis->exec();

        return array('qbeans'=>$data[1],'contributer'=>$data[4]);
    }

    public function getFollowq($uid,$offset,$limit)
    {
        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $data = $redis->sMembers('user:'.$uid.'.follows');

        if (!empty($data)){
            $qdata = $this->db->select('q.id,q.question,q.description,q.isresponsed,u.userName,u.userIcon')->from('comm_question as q')
                ->join('mod_user as u','q.uid = u.uid','left')
                ->where_in('q.id',$data)
                ->where(array('q.status'=>1))
                ->order_by('q.created','DESC')
                ->limit($limit,$offset)
                ->get()->result_array();

            $length = count($qdata);
            if ($length<$limit) $end = 1;
            else $end = 0;

            if ($length !== 0){
                $redis->multi();
                foreach ($qdata as $row){
                    $redis->hMGet('question:'.$row['id'],array('views','follows'));
                }
                $data2 = $redis->exec();
                /*重构数据*/
                foreach ($qdata as $k=>&$row) {
                    $row['userIcon'] = preg_match("/http:\/\//i",$row['userIcon'])>0?$row['userIcon']:$this->_resource_url.$row['userIcon'];
                    $row['views'] = $this->formatnum($data2[$k]['views'],'views',$row['id']);
                    $row['follows'] = $this->formatnum($data2[$k]['follows']);
                }
            }
        }else{$qdata=array();$end=1;}

        return array('question'=>$qdata,'end'=>$end);
    }

    public function getFollowsub($uid,$offset,$limit)
    {
        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $data = $redis->sMembers('user:'.$uid.'.subfollows');

        if (!empty($data)){
            $subdata = $this->db->select('id,name,icon')->from('comm_subject')
                ->where_in('id',$data)
                ->where_in('status',array(1,2))
                ->limit($limit,$offset)
                ->get()->result_array();

            $length = count($subdata);
            if ($length<$limit) $end = 1;
            else $end = 0;

            if ($length !== 0){
                /*重构数据*/
                foreach ($subdata as &$row) {
                    $row['icon'] = $this->_resource_url.$row['icon'];
                }
            }
        }else{$subdata=array();$end=1;}

        return array('subject'=>$subdata,'end'=>$end);
    }

    public function getCollectAnswer($uid,$offset,$limit)
    {
        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $data = $redis->sMembers('user:'.$uid.'.collects');

        if (!empty($data)){
            $adata = $this->db->select('a.id,a.qid,a.answer,q.question,u.userName,u.userIcon')->from('comm_answer as a')
                ->join('comm_question as q','q.id = a.qid','left')
                ->join('mod_user as u','u.uid = a.uid','left')
                ->where_in('a.id',$data)
                ->where(array('q.status'=>1))
                ->order_by('a.created','DESC')
                ->limit($limit,$offset)
                ->get()->result_array();

            $length = count($adata);
            if ($length<$limit) $end = 1;
            else $end = 0;

            if ($length !== 0){
                /*重构数据*/
                foreach ($adata as $k=>&$row) {
                    $row['userIcon'] = preg_match("/http:\/\//i",$row['userIcon'])>0?$row['userIcon']:$this->_resource_url.$row['userIcon'];
                }
            }
        }else{$adata=array();$end=1;}

        return array('answer'=>$adata,'end'=>$end);
    }

    public function getUserAnswer($uid,$offset,$limit)
    {
        $adata = $this->db->select('a.answer,a.qid,a.id,q.question')->from('comm_answer as a')
            ->join('comm_question as q','q.id = a.qid','left')
            ->where('a.uid',$uid)
            ->where(array('q.status'=>1))
            ->order_by('a.created','DESC')
            ->limit($limit,$offset)
            ->get()->result_array();

        $length = count($adata);
        if ($length<$limit) $end = 1;
        else $end = 0;

        if ($length !== 0){
            $this->load->model('redis_model');
            $redis = $this->redis_model->getRedisInstance();
            $redis->multi();
            foreach ($adata as $row){
                $redis->hMGet('answer:'.$row['id'],array('agrees','comments'));
            }
            $data = $redis->exec();
            /*重构数据*/
            foreach ($adata as $k=>&$row) {
                $row['agrees'] = $data[$k]['agrees'];
                $row['comments'] = $data[$k]['comments'];
            }
        }

        return array('answer'=>$adata,'end'=>$end);
    }

    public function getUserQuestion($uid,$offset,$limit)
    {
        $qdata = $this->db->select('id,question,description,isresponsed')->from('comm_question')
            ->where('uid',$uid)
            ->where(array('status'=>1))
            ->order_by('created','DESC')
            ->limit($limit,$offset)
            ->get()->result_array();

        $length = count($qdata);
        if ($length<$limit) $end = 1;
        else $end = 0;

        if ($length !== 0){
            $this->load->model('redis_model');
            $redis = $this->redis_model->getRedisInstance();
            $redis->multi();
            foreach ($qdata as $row){
                $redis->hMGet('question:'.$row['id'],array('views','follows'));
            }
            $data = $redis->exec();
            /*重构数据*/
            foreach ($qdata as $k=>&$row) {
                $row['views'] = $this->formatnum($data[$k]['views'],'views',$row['id']);
                $row['follows'] = $this->formatnum($data[$k]['follows']);
            }
        }

        return array('question'=>$qdata,'end'=>$end);
    }

    public function getAudio($qid)
    {
        $res = $this->db->get_where('comm_answer_audio',array('qid'=>$qid),1)->row_array();
        $res['audio'] = explode('|',$res['audio']);
        $res['audio'] = $this->_media_url.$res['audio'][0];
        return $res;
    }
    public function getMultiAudio($qid)
    {
        $res = $this->db->get_where('comm_answer_audio',array('qid'=>$qid),1)->row_array();
        $res['audio'] = explode('|',$res['audio']);
        $res['note'] = explode('|',$res['note']);
        $audios = array();
        $titles = array();
        $notes = array();
        $index = 1;
        foreach ($res['audio'] as $v){
            $titles[] = $res['title'].$index;
            $audios[] = $this->_media_url.$v;
            $index++;
        }
        foreach ($res['note'] as $n){
            $notes[] = $this->_resource_url.$n;
        }
        return array('title'=>$res['title'],'audios'=>$audios,'titles'=>$titles,'notes'=>$notes);
    }

    public function sharecallback($data)
    {
        $str = igbinary_serialize($data);
        $this->load->model("redis_model");
        $redis = $this->redis_model->getRedisInstance();
        $redis->rPush('shareoplist',$str);

        $res['firstshare'] = false;
        if ($redis->getBit('comm:firstshare',$data['uid'])==0){
            $redis->multi()
                ->setBit('comm:firstshare',$data['uid'],1)
                ->incrBy('user:'.$data['uid'].'.beans',100)
                ->exec();
            $res['firstshare']=true;
        }
        return $res;
    }

    public function changeIcon($uid,$icon)
    {
        $data['userIcon'] = $icon;
        return $this->db->update('mod_user',$data,'uid='.$uid);
    }

    public function getProfile($uid)
    {
        $uinfo = $this->db->select('u.userName,u.userIcon,ui.userGender,u.telNum,u.wx_num,u.email,ui.birthDay,ui.eduLevel,ui.livecity,ui.livearea')
            ->from('mod_user as u')
            ->join('mod_user_info as ui','ui.uid=u.uid','left')
            ->where('u.uid=',$uid)
            ->get()->row_array();
        $uinfo['userIcon']=preg_match("/http:\/\//i",$uinfo['userIcon'])>0?$uinfo['userIcon']:$this->_resource_url.$uinfo['userIcon'];
        $childinfo = $this->db->select('*')->from('mod_child_info')
            ->where('uid=',$uid)->get()->result_array();
        $res['user'] = $uinfo;
        foreach ($childinfo as &$c){
            $c['genderstr'] = ($c['gender']=='m')?'男孩':'女孩';
            $c['schoolstr'] = ($c['school']==1)?'公立学校':($c['school']=='2'?'私立学校':'国际学校');
        }
        $res['child'] = $childinfo;
        return $res;
    }

    public function updateProfile($uid,$user,$userinfo,$childinsert,$childdel)
    {
        $res = array('status'=>true,'firstprofile'=>false);

        $this->db->trans_start();
        if (!empty($user)) $this->db->update('mod_user',$user,'uid ='.$uid);
        if (!empty($userinfo)) $this->db->update('mod_user_info',$userinfo,'uid ='.$uid);
        if (!empty($childinsert)) $this->db->insert_batch('mod_child_info',$childinsert);
        if (!empty($childdel)) {
            foreach ($childdel as $del){
                $this->db->delete('mod_child_info',array('id'=>(int)$del));
            }
        };
        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE)
        {
            $res['status']=false;
        }

        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        if ($redis->getBit('comm:firstprofile',$uid)==0){
            $redis->multi()
                ->setBit('comm:firstprofile',$uid,1)
                ->incrBy('user:'.$uid.'.beans',100)
                ->exec();
            $res['firstprofile']=true;
        }

        return $res;
    }

    public function resizeImg($filepath,$width,$height)
    {
        //处理图片
        $config['source_image'] = $filepath;
        $config['width']     = $width;
        $config['height']   = $height;
        $config['maintain_ratio'] = true;
        $config['master_dim'] = 'auto';
        $this->load->library('image_lib', $config);
        return $this->image_lib->resize();
    }

    public function getNotifyUnread($uid)
    {
        $this->load->model("redis_model");
        $redis = $this->redis_model->getRedisInstance();
        $redis->multi();
//        $redis->zRange('sysnotify',0,-1);
        $redis->zRevRange('sysnotify',0,9);
        $redis->zCard('user:'.$uid.'.notify.unread');
        $data = $redis->exec();

        $sys = 0;
        foreach ($data[0] as $msgid){
            $isread = $redis->getBit('sysnotify:'.$msgid,$uid);
            if ($isread==0) $sys++;
        }
        $user = (int)$data[1];
        $unread = $sys+$user;
        return array('sys'=>$sys,'user'=>$user,'unread'=>$unread);
    }

    public function getUserNotify($uid,$start,$end,$limit)
    {
        $this->load->model("redis_model");
        $redis = $this->redis_model->getRedisInstance();
        $data=$redis->zRevRange('user:'.$uid.'.notify.unread',$start,$end);

        $notify = array();
        foreach ($data as $msgid){
            $item['msgid']=$msgid;
            $msg=$redis->get('notifymsg:'.$msgid);
            $item['msg']=igbinary_unserialize($msg);
//            $item['msg']['created']=date('Y-m-d H:i:s',$item['msg']['created']);
            $item['msgtype']='user';
            $notify[]=$item;
        }
        $length = count($data);
        if ($length<$limit) $end = 1;
        else $end = 0;

        return array('notify'=>$notify,'end'=>$end);
    }

    public function getSysnotify($uid,$start,$end,$limit)
    {
        $this->load->model("redis_model");
        $redis = $this->redis_model->getRedisInstance();
        $data=$redis->zRevRange('sysnotify',$start,$end);

        $notify = array();
        foreach ($data as $msgid){
            $item=array();
            $isread = $redis->getBit('sysnotify:'.$msgid,$uid);
            if ($isread==0){
                $item['msgid']=$msgid;
                $msg=$redis->get('notifymsg:'.$msgid);
                $item['msg']=igbinary_unserialize($msg);
//                $item['msg']['created']=date('Y-m-d H:i:s',$item['msg']['created']);
                $item['msgtype']='sys';
                $notify[]=$item;
            }
        }
//        $length = count($data);
//        if ($length<$limit) $end = 1;
//        else $end = 0;
        $end=1;

        return array('notify'=>$notify,'end'=>$end);
    }

    public function readNotify($uid,$msgid,$msgtype)
    {
        $this->load->model("redis_model");
        $redis = $this->redis_model->getRedisInstance();
        switch ($msgtype){
            case 'sys':
                $redis->setBit('sysnotify:'.$msgid,$uid,1);
                break;
            case 'user':
                $redis->zRem('user:'.$uid.'.notify.unread',$msgid);
                break;
        }
        return;
    }

    public function clearNotify($uid)
    {
        $this->load->model("redis_model");
        $redis = $this->redis_model->getRedisInstance();
        $redis->zRemRangeByRank('user:'.$uid.'.notify.unread',0,-1);
        return;
    }
}